package com.example.im.mvp.presenter

import android.app.Activity
import android.content.Context
import com.example.im.xmpp.IMConnection
import com.example.im.common.Constants
import com.example.im.entity.FriendOrRoom
import com.example.im.http.APIRetrofit
import com.example.im.http.RetrofitManager
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IMainView
import com.example.im.utils.ACache
import com.example.im.utils.LogUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers

class MainPresenter(mContext: Context, mView: IMainView?) :
    BasePresenter<IMainView>(mContext, mView) {

    private var imConnection: IMConnection? = null

    init {
        imConnection = IMConnection.instance
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    fun automaticLogin() {

        if (imConnection!!.isAuthenticated) {
            getView().isAuthenticated(true)
            return
        }

        val preferences = getContext()
            .getSharedPreferences(Constants.ACCOUNT_ATTRIBUTES, Context.MODE_PRIVATE)

        val userName = preferences.getString(Constants.ACCOUNT_USER_NAME, null)
        val password = preferences.getString(Constants.ACCOUNT_PASSWORDS, null)

        if (userName == null && password == null) {
            getView().isAuthenticated(false)
            return
        }

        val observable = Observable.zip(Observable.just(userName), Observable.just(password),
            BiFunction<String, String, Boolean> { t1, t2 ->
                imConnection!!.login(t1, t2)
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    getView().isAuthenticated(it)
                },
                {
                    getView().onHint(it.message!!)
                    getView().onAutomaticLoginStart("连接失败")
                },
                { getView().onAutomaticLoginEnd() },
                { getView().onAutomaticLoginStart("连接已被断开，正在重新连接...") }
            )
        this.disposable.add(observable)

    }

    fun mainApplyPermissions(activity: Activity) {
        val observable = this.applyPermissions(activity)
            .subscribe {
                if (!it) getView().onHint("该应用需要访问部分权限，请到 “应用信息 -> 权限” 中授予！")
            }
        this.disposable.add(observable)
    }

    fun automaticAddUser() {

        val aCache = ACache.get(getContext())
        val inviteCode = aCache.getAsString("INVITE_CODE")
            ?: return

        val observable = Observable.just(inviteCode)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.userSearch(it)
            }
            .filter {
                it.isNotEmpty()
            }
            .flatMap {
                Observable.fromIterable(it)
                    .lastElement()
                    .toObservable()
            }
            .map {
                with(FriendOrRoom(), {
                    this.jid = it.getValues("jid")[0].toString()
                    this.account = it.getValues("Username")[0].toString()
                    this.nickname = it.getValues("Name")[0].toString()
                    this.getFriendOrRoom()
                })
            }
            .map {
                imConnection!!.createEntry(it.account!!, it.nickname!!)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it) {
                        aCache.clear()
                    }
                },
                { LogUtils.e(it.message) }
            )
        this.disposable.add(observable)

    }

}